package com.guigu.youxuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.youxuan.mapper.BackRoleMenuMapper;
import com.guigu.youxuan.pojo.BackRoleMenu;
import com.guigu.youxuan.service.IBackRoleMenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liweixin
 * @since 2024-05-15
 */
@Service
public class BackRoleMenuServiceImpl extends ServiceImpl<BackRoleMenuMapper, BackRoleMenu> implements IBackRoleMenuService {

    @Override
    public long[] queryMenuIdByRoleId(Long roleId) {
        QueryWrapper<BackRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<BackRoleMenu> list = this.list(queryWrapper);
        // 使用Java 8的流API
        long[] idArray = list.stream()
                .mapToLong(BackRoleMenu::getMenuId) // 直接映射为LongStream
                .toArray(); // 生成long数组

        return idArray;
    }

    @Override
    public void updateRoleMenuByRid(List<Long> menuIdList, Long roleId) {
        QueryWrapper<BackRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<BackRoleMenu> list = this.list(queryWrapper);
        for(BackRoleMenu rw : list) {
            this.removeById(rw);
        }
        for(Long menuId : menuIdList) {
            BackRoleMenu rw = new BackRoleMenu();
            rw.setMenuId(menuId);
            rw.setRoleId(roleId);
            this.save(rw);
        }
    }
}
